<?php
class InterceptsController extends AppController {

	var $name = 'Intercepts';
	
	var $errorz = array();
	var $twitterSinceId = null;
	
	function isAuthorized(){
		if(in_array($this->action, array(
													'gettimeline'
													//'getTimelineByFacebook'	//betűméret érzékeny és a js-ben kis betűkkel hívjuk
													))){
			return true;
		}
		return false;		//minden más tiltva
	}

/*
 * Get timelines for different social networks
 * @access public
 * @permission user level
 * @return array $timeline
 * 	[Message] => Array(
 * 	     [message] => RT @iamdiddy Check out this tribute to Michael Jackson feat Myself,Game,Chris Brown,Polo, Mario Winans Boyz II Men http://tinyurl.com/kow5e7
 * 			[created] => 2009-06-27 14:41:03)
 * 	[Account] => Array(
 * 			[0] => Array(
 * 					[id] => 23
 * 					[Community] => Array(
 * 								[name] => twitter)
 * 					[username] => tsabeeka
 * 					[avatar] => http://s3.amazonaws.com/twitter_production/profile_images/20706232/tvmaci2_normal.jpg
 *						[url] => http://turulcsirip.hu/user/tsabeeka
 *					))
 *
 *	$timeline is the timeline and $intercepts are the new entries
*/	
	function getTimeline(){
		$this->Intercept->Account->unbindModel(array('belongsTo' => array('User'), 'hasMany' => array('Intercept')));
		$accounts = $this->Intercept->Account->find('all',
														  array(
																'conditions' => array('Account.user_id' => $this->Auth->user('id'))
																));
		//debug($accounts);
		$this->_curlInit();
		$timeline = $error = array();
		foreach($accounts as $account){
			if($account['Account']['gettimeline']){
				switch($account['Community']['name']){
					case 'twitter':
						//get last saved id for this account
						$this->Intercept->unBindModel(array('belongsTo' => array('Account')));
						//debug($account);
						$this->twitterSinceId = $this->Intercept->find('first', array(
																'conditions' => array('account_id' => $account['Account']['id']),
																'fields' => array('there_id', 'created'),
																'order' => '(10000000000000 + there_id) DESC'
																));
						$tl_search = $this->_getSearchTwitter($account);	//this should be first otherwise friends timeline since id do not let to get most of the foreign replies
						$tl = $this->_getTimelineByTwitter($account);	//if we have timeline $tl will contain
						$tl_direct = $this->_getTimelineByTwitter($account, false);
						if($tl && $tl_direct){		//if we have friends timeline and direct message
							$tl = array_merge($tl, $tl_direct);
						}
						elseif($tl_direct){	//no timeline but there are new direct messages
							$tl = $tl_direct;
						}
						if(is_array($tl_search))
							$tl = array_merge($tl, $tl_search);
						break;
					case 'iwiw':
						$tl = $this->_getTimelineByIwiw($account);
						break;
					case 'facebook':
						$tl = $this->_getTimelineByFacebook($account);
						break;						
					default:
						$tl = new Object;
						$tl->error = 'UnIntegrated community: ' . $account['Community']['name'];
				}
				//debug($tl);
				if(isset($tl->error))
					array_push($error, $tl->error);
				elseif(is_array($tl)){
					$timeline = array_merge($timeline, $tl);
				}
			}
		}
		
		$timelineFiltered = $intercepts = array();
		//debug($timeline);
		foreach($timeline as $t){
			//filter out messages sent by ourself via sociall
			$t['created'] = $t['Message']['created'];
			if($t['Account'][0]['Community']['name'] == 'twitter'){
				if(!isset($t['Message']['source']) || !strpos($t['Message']['source'], 'sociall') || $t['Account'][0]['username'] != $t['Account'][0]['targetuser']){
					$timelineFiltered[] = $t;
				}
			}
			else
				$timelineFiltered[] = $t;
			$intercepts[] = array(
									'account_id' => $t['Account'][0]['id'],
									'sender' => $t['Account'][0]['username'],
									'avatar' => $t['Account'][0]['avatar'],
									'created' => $t['Message']['created'],
									'there_id' => $t['Message']['id'] ? $t['Message']['id'] : 0,
									'message' => $t['Message']['message'],
									'reply' => isset($t['Message']['reply']) ? $t['Message']['reply'] : null,
									'extra' => isset($t['Message']['extra']) ? $t['Message']['extra'] : false,
									);
		}
		//debug($intercepts);
		if(isset($intercepts[0])){
			$this->Intercept->saveAll($intercepts, array('validate' => true, 'atomic' => false));	//validate each record but they could be saved one by one (no transaction needed)
		}
		
		//debug($timeline);
		if(count($this->errorz))
			array_push($error, $this->errorz);
		//debug($error);
		$this->set('error', $error);
		$timelineFiltered = $this->array_msort($timelineFiltered, array('created'=> SORT_DESC));
		$this->set('timeline', $timelineFiltered);
		
		if(count($error))
			$this->log('intercepts :: ' . print_r($error, true), LOG_DEBUG);
		
		$this->_curlFinish();
	}

/*
 * Get's the friends timeline or direct messages from twitter
 * @param array $account all neccesarry information to log in to the given social network
 * 		[Account] => Array(
 *            [username] => rrd108@gmail.com
 *            [pass] => YWRuaXZvZzQ1Mytqc2RsYSVmam89RlNpZyFpbTlDYWdGMEcyUmludkQ=)
 *         [Community] => Array(
 *            [name] => iwiw)
 * @param bool $friendsTimeline asking for friends timeline (true, default) or new direct messages (false)
 * @access private
 * @permission user level
 * @return bool true on success
*/
	function _getTimelineByTwitter($account, $friendsTimeline = true){
		App::import('Vendor', 'twitterOAuth', array('file' => 'twitterOAuth.php'));
		$secrets = unserialize($account['Account']['extras']);
		$secrets = array(
							'oauth_token' => $this->_decodePass($secrets['oauth_token']),
							'oauth_token_secret' => $this->_decodePass($secrets['oauth_token_secret'])
							);

		$twitterOAuth = new TwitterOAuth(
										$this->Option->field('value', array('name' => 'twitter_consumer_key')),
										$this->Option->field('value', array('name' => 'twitter_secret_key')),
										$secrets['oauth_token'],
										$secrets['oauth_token_secret']);

		if(!$friendsTimeline){
			$sinceId = $this->Intercept->find('first', array(
																		'conditions' => array('account_id' => $account['Account']['id'],
																									'extra' => 'd'),
																		'fields' => 'there_id',
																		'order' => '(10000000000000 + there_id) DESC'
																		));
			//append to the url. if the id is older than the last 20 messages we just get the last 20
		}
		$url = $friendsTimeline ? 'https://twitter.com/statuses/friends_timeline.json' : 'https://twitter.com/direct_messages.json';

		//get last saved id for this account
		//append to the url if the id is older than the last 20 messages we just get the last 20
		$postData = array();
		if(isset($sinceId['Intercept']['there_id'])){
			$postData = array('since_id' => $sinceId['Intercept']['there_id']);
		}
		elseif($this->twitterSinceId['Intercept']['there_id'])
			$postData = array('since_id' => $this->twitterSinceId['Intercept']['there_id']);

		/*$twitter_timeline = json_decode(
											$twitterOAuth->OAuthRequest(
																	$url,
																	$postData,
																	'GET'));*/
		$twitter_timeline = $twitterOAuth->get($url,$postData);
		if(!isset($twitter_timeline)){
			$twitterError = array(
									'type' => 'twitterError',
									'data' => array(
														'time' => date('Y-m-d H:i:s'),
														'account' => $account['Account']['id'],
														'responseCode' => null,
														'message' => __('Twitter connection error', true)
														)
									);
			array_push($this->errorz, $twitterError);
			return false;
		}
		if(isset($twitter_timeline->error)){
			$twitterError = array(
									'type' => 'twitterError',
									'data' => array(
														'time' => date('Y-m-d H:i:s'),
														'account' => $account['Account']['id'],
														'responseCode' => null,
														'message' => $twitter_timeline->request . ' :: ' . $twitter_timeline->error
														)
									);
			//debug($twitterError);
			array_push($this->errorz, $twitterError);
			return false;
		}
		//we should standardize the timeline output which is ok for all networks
				/*
		friends_timeline response:
		 [0] => stdClass Object
        (
            [in_reply_to_screen_name] => 
            [geo] => 
            [source] => <a href="http://83degrees.com/to/powertwitter" rel="nofollow">Power Twitter</a>
            [created_at] => Fri Oct 02 16:07:12 +0000 2009
            [truncated] => 
            [in_reply_to_status_id] => 
            [user] => stdClass Object
                (
                    [statuses_count] => 1478
                    [favourites_count] => 6
                    [profile_sidebar_fill_color] => FFBC84
                    [description] => IBM's premier Web site for Java, Android, Linux, Open Source, PHP, Social, Cloud Computing, Google, jQuery, and Web developer educational resources
                    [url] => http://bit.ly/EQ7te
                    [following] => 1
                    [profile_sidebar_border_color] => E15018
                    [notifications] => 
                    [created_at] => Fri Sep 19 13:10:39 +0000 2008
                    [geo_enabled] => 
                    [profile_text_color] => 333333
                    [profile_background_image_url] => http://a3.twimg.com/profile_background_images/3074417/dWbackground_v2g.jpg
                    [profile_link_color] => 010bb7
                    [followers_count] => 15735
                    [protected] => 
                    [profile_image_url] => http://a1.twimg.com/profile_images/60341510/dWbadge_v2_normal.jpg
                    [profile_background_tile] => 
                    [location] => 
                    [name] => developerworks
                    [friends_count] => 16138
                    [profile_background_color] => ffffff
                    [screen_name] => developerworks
                    [id] => 16362921
                    [verified] => 
                    [time_zone] => Pacific Time (US & Canada)
                    [utc_offset] => -28800
                )

            [favorited] => 
            [id] => 4556082020
            [in_reply_to_user_id] => 
            [text] => Learn how to get data in and out of #Grails #applications & #Atom syndication feed &gt; bit.ly/4aMvGS #web
        )

        
        
        *******************



			direct messages response:
					 [0] => stdClass Object
        (
            [text] => Van dropboxod?
            [sender] => stdClass Object
                (
                    [friends_count] => 64
                    [description] => Patterns and pixels. Everywhere.
                    [utc_offset] => 12600
                    [statuses_count] => 746
                    [created_at] => Tue Jul 10 01:59:30 +0000 2007
                    [profile_text_color] => 333333
                    [notifications] => 
                    [profile_background_image_url] => http://s3.amazonaws.com/twitter_production/profile_background_images/19100427/grass-field.jpg
                    [favourites_count] => 3
                    [time_zone] => Tehran
                    [profile_link_color] => 0084B4
                    [url] => http://carbonbased.hu
                    [name] => Krisztian Szilagyi
                    [profile_background_tile] => 
                    [protected] => 
                    [verified] => 
                    [profile_background_color] => 9AE4E8
                    [profile_sidebar_fill_color] => DDFFCC
                    [profile_image_url] => http://s3.amazonaws.com/twitter_production/profile_images/265393407/free_iran_normal.jpg
                    [following] => 1
                    [followers_count] => 90
                    [location] => TEHRAN
                    [id] => 7359812
                    [profile_sidebar_border_color] => BDDCAD
                    [screen_name] => pegazoo
                )

            [created_at] => Mon Jun 29 12:06:34 +0000 2009
            [sender_id] => 7359812
            [sender_screen_name] => pegazoo
            [recipient_id] => 12460092
            [recipient_screen_name] => rrd
            [recipient] => stdClass Object
                (
                    [friends_count] => 103
                    [description] => Webmánia Creative Consulting - a webfejlesztés mindennapjai
                    [utc_offset] => 3600
                    [statuses_count] => 874
                    [created_at] => Sun Jan 20 15:19:07 +0000 2008
                    [profile_text_color] => 634047
                    [notifications] => 
                    [profile_background_image_url] => http://static.twitter.com/images/themes/theme3/bg.gif
                    [favourites_count] => 0
                    [time_zone] => Budapest
                    [profile_link_color] => 088253
                    [url] => http://webmania.cc
                    [name] => rrd
                    [profile_background_tile] => 
                    [protected] => 
                    [verified] => 
                    [profile_background_color] => EDECE9
                    [profile_sidebar_fill_color] => E3E2DE
                    [profile_image_url] => http://s3.amazonaws.com/twitter_production/profile_images/83929107/rrd_normal.jpg
                    [following] => 
                    [followers_count] => 202
                    [location] => Somogyvámos, Hungary
                    [id] => 12460092
                    [profile_sidebar_border_color] => D3D2CF
                    [screen_name] => rrd
                )
            [id] => 204884030
        )
		*/
		//debug($twitter_timeline);
		if($twitter_timeline){
			$i = 0;
			foreach($twitter_timeline as $t){
				$timeline[$i] = array(
									'Message' => array(
														'message' => $t->text,
														'created' => date('Y-m-d H:i:s', strtotime($t->created_at)),
														'id' => $t->id,
														'source' => isset($t->source) ? $t->source : null,
														'reply' => isset($t->in_reply_to_status_id) ? $t->in_reply_to_status_id : null,
														'extra' => $friendsTimeline ? false : 'd'
														),
									'Account' => array(
														array(
															'id' => $account['Account']['id'],
															'Community' => array(
																					'name' => 'twitter'
																					),
															'username' => $friendsTimeline ? $t->user->screen_name : $t->sender->screen_name,
															'avatar' => $friendsTimeline ? $t->user->profile_image_url : $t->sender->profile_image_url,
															'url' => 'http://turulcsirip.hu/user/' . ($friendsTimeline ? $t->user->screen_name : $t->sender->screen_name),
															'targetuser' => $account['Account']['username']
															)
														)
									);
				$i++;
			}
			//debug($timeline);
			return $timeline;
		}
		return false;
	}

/*
 * Get's the search results from twitter
 * @param array $account all neccesarry information to log in to the given social network
 * 		[Account] => Array(
 *            [username] => rrd108@gmail.com
 *            [pass] => YWRuaXZvZzQ1Mytqc2RsYSVmam89RlNpZyFpbTlDYWdGMEcyUmludkQ=)
 *         [Community] => Array(
 *            [name] => iwiw)
 * @param bool $friendsTimeline asking for friends timeline (true, default) or new direct messages (false)
 * @access private
 * @permission user level
 * @return bool true on success
*/		
	function _getSearchTwitter($account, $searchterm = null){
		//make searches in every 10 minutes
		$searchTime = '-10 minutes';
		$lastSearch = $this->Option->find('first', array(
																	'conditions' => array('name' => 'search_' . $account['Account']['username'])
																	));
		//debug($lastSearch);
		if(!$lastSearch || $lastSearch['Option']['value'] < strtotime($searchTime)){
			$this->Option->save(array(
											'name' => 'search_' . $account['Account']['username'],
											'value' => time()
											));
			curl_setopt($this->cp, CURLAUTH_NTLM, true);
			//curl_setopt($this->cp, CURLOPT_USERPWD, $account['Account']['username'] . ':' . $this->_decodePass($account['Account']['pass']));
			curl_setopt($this->cp, CURLOPT_HTTPGET, true);

			$url = $searchterm ? 'http://search.twitter.com/search.json?q=' . $searchterm : 'http://search.twitter.com/search.json?q=%40' . $account['Account']['username'];
		
			//append to the url. if the id is older than the last 20 messages we just get the last 20
			$sinceId = $this->Intercept->find('first', array(
																		'conditions' => array(
																								'account_id' => $account['Account']['id'],
																								'created <' => date('Y-m-d H:i:s', strtotime($searchTime))
																								),
																		'fields' => 'there_id',
																		'order' => '(10000000000000 + there_id) DESC'
																		));
			
			$intercepted = array();
			
			if($sinceId['Intercept']['there_id']){
				$url .= '&since_id=' . $sinceId['Intercept']['there_id'];
	
				//we should get the there_ids from the last 10 minutes also
				$newIds = $this->Intercept->find('all', array(
																		'conditions' => array(
																								'account_id' => $account['Account']['id'],
																								'there_id >' => $sinceId['Intercept']['there_id']
																								),
																		'fields' => 'there_id'
																		));
				foreach($newIds as $n){
					$intercepted[] = $n['Intercept']['there_id'];
				}
			}
			//debug($url);	//2341130067
			curl_setopt($this->cp, CURLOPT_URL, $url);
			

			$twitter_timeline = $twitter_tline = false;
			$twitter_tline = json_decode(curl_exec($this->cp));
			//debug($twitter_tline);
			//$this->log(print_r($twitter_timeline, true), LOG_DEBUG);
			if($twitter_tline && is_array($twitter_tline->results)){
				if(isset($twitter_tline->error)){
					array_push($this->errorz, $twitter_tline->error);
					return false;
				}
				else{
					$i = 0;
					foreach($twitter_tline->results as $t){
						if(isset($t->text)){
							if(!in_array($t->id, $intercepted)){
								//lets filter out if the message is already intercepted
								$twitter_timeline[$i] = array(
										'Message' => array(
														'message' => $t->text,
														'created' => date('Y-m-d H:i:s', strtotime($t->created_at)),
														'id' => $t->id,
														'source' => $t->source,
														'extra' => false
														),
										'Account' => array(
														array(
															'id' => $account['Account']['id'],
															'Community' => array(
																					'name' => 'twitter'
																					),
															'username' => $t->from_user,
															'avatar' => $t->profile_image_url,
															'url' => 'http://turulcsirip.hu/user/' . $t->from_user,
															'targetuser' => $account['Account']['username']
															)
														)
									);
								$i++;
							}
						}
					}
				}
				//debug($twitter_timeline);
				return $twitter_timeline;
			}
			else
				return false;
		}
	}
	
/*
 * Get's the "üzenőfal" from iwiw
 * @param array $account all neccesarry information to log in to the given social network
 * 		[Account] => Array(
 * 				[id] => 23
 *            [username] => rrd108@gmail.com
 *            [pass] => YWRuaXZvZzQ1Mytqc2RsYSVmam89RlNpZyFpbTlDYWdGMEcyUmludkQ=)
 *         [Community] => Array(
 *            [name] => iwiw)
 * @access private
 * @permission user level
 * @return bool true on success
 * @restriction Strictly depend on iwiw html output as we have no API on this. If iwiw change the layout we will not get the timeline
*/		
	function _getTimelineByIwiw($account){
		//debug($account);
		App::import('Vendor', 'iwiw');
		$iwiwSid = $this->Session->read('iwiwSid.acc_'.$account['Account']['id']);
		$iwiw = new Iwiw($iwiwSid);
//		debug($iwiw);
		$iwiwLogin = $account['Account'];
		$iwiwLogin['pass'] = $this->_decodePass($iwiwLogin['pass']);
		$iwiwSid = $iwiw->login($iwiwLogin);
//		debug($iwiw);
		$iwiwMessages = $iwiw->getTimeLine();
		if($iwiwMessages){
			$this->Session->write('iwiwSid.acc_'.$account['Account']['id'], $iwiwSid);
			//debug($iwiwMessages);
			/*
			[0] => Array
	        (
	            [username] => Imre Cs. [Candan...
	            [url] => http://iwiw.hu/pages/user/userdata.jsp?userID=12298250
	            [message] => Az 5 legkevésbé hihető újsághír:
						1. Orbán Viktor Gyurcsány Ferencet kérte fel tizedik gyereke keresztapjának.
						2. A Magyar Tudományos Akadémia örökös tagjává választotta Fekete Pákót.
						3. Demszky Gá...
	            [created] => 2009-06-26
	        )
			*/
			$timeline = array();
			foreach($iwiwMessages as $m){
				//as on iwiw there is no unique id for the messages we should check it in the database
				$uniqueId = md5($m['username'].mb_substr($m['message'], 0, 100));
				$this->Intercept->unbindModel(array('belongsTo' => array('Account')));
				$isSaved = $this->Intercept->find('count',
										  array(
												'conditions' => array('there_id' => $uniqueId)
												));
//$this->log('iwiw isSaved: ' . gettype($isSaved) . ' :: ' . $uniqueId . ' :: ' . $isSaved, LOG_DEBUG);
				if($isSaved === 0){	//count sometimes gave back false when we have the there_id so we should check for the type also
					$timeline[] = array(
									'Message' => array(
														'message' => $m['message'],
														'created' => $m['created'],
														'id' => $uniqueId		//generated unique id
														),
									'Account' => array(
														0 => array(
																	'id' => $account['Account']['id'],
																	'Community' => array('name' => 'iwiw'),
																	'username' => $m['username'],
																	'avatar' => './img/no_avatar.png',
																	'url' => $m['url'],
																	'targetuser' => $account['Account']['username']
																	)
														)
									);
				}
			}
			if(count($timeline))
				return $timeline;
			else
				return false;
		}
		else{
			$iwiwError = array('type' => 'iwiwError',
									 'data' => array(
														'time' => date('Y-m-d H:i:s'),
														'account' => $account['Account']['id'],
														'message' => $iwiw->responseCode
														));
			array_push($this->errorz, $iwiwError);
			return false;
		}
	}

/*
 * Get stream from facebook
 * @param array $account all neccesarry information to log in to the given social network
 * 		[Account] => Array(
 * 				[id] => 23
 *            [username] => rrd108@gmail.com
 *            [pass] => YWRuaXZvZzQ1Mytqc2RsYSVmam89RlNpZyFpbTlDYWdGMEcyUmludkQ=)
 *         [Community] => Array(
 *            [name] => iwiw)
 * @access private
 * @permission user level
 * @return bool true on success
*/		
	function _getTimelineByFacebook($account){
		App::import('Vendor', 'facebook');
		$api_key = '8acabeec69a20a846d2d7b40e9df9fa2';
		$secret = $this->Option->field('value', array('name' => 'facebook_secret_key'));
		$facebook = new Facebook($api_key, $secret);
		$user = unserialize($account['Account']['extras']);
		$facebook->set_user($user['userId'], $account['Account']['pass']);

		
		$since = $this->Intercept->find('first', array(
																	'conditions' => array('account_id' => $account['Account']['id']),
																	'fields' => 'UNIX_TIMESTAMP(created) AS created',
																	'order' => 'created DESC'
																	));
		//debug($since);
		$since = isset($since[0]['created']) ? $since[0]['created'] : strtotime('-5 days');
		try {
			$facebook_timeline = $facebook->api_client->stream_get(null, null, $since, null, 30);
		}
		catch(Exception $e){
			$facebookError = array(
										'type' => 'facebookError',
										'data' => array(
														'time' => date('Y-m-d H:i:s'),
														'account' => $account['Account']['id'],
														'message' => $e->getMessage()
														)
										);
			array_push($this->errorz, $facebookError);
			//debug($e->getMessage());
			return false;
		}
		//debug($facebook_timeline);
		
		//we should find what is saved as we would get back already saved messages if they have new comment
		$saved = $this->Intercept->find('all', array(
																	'conditions' => array('account_id' => $account['Account']['id']),
																	'fields' => 'there_id',
																	'order' => 'created DESC',
																	'limit' => 30
																));
		$_saved = array();
		foreach($saved as $s){
			$_saved[] = $s['Intercept']['there_id'];
		}
		$saved = $_saved;
		//debug($saved);
		
		$timeline = array();
		if($facebook_timeline && is_array($facebook_timeline['posts'])){
			foreach($facebook_timeline['posts'] as $t){
				$user = $facebook->api_client->users_getInfo($t['actor_id'], 'name, pic_small');
				//debug($user);
				if(isset($user[0]) && !in_array($t['post_id'], $saved)){	//the user exists, and the post is not saved yet
					$timeline[] = array(
									'Message' => array(
														'message' => $t['message'] ? $t['message'] : $t['permalink'],
														'created' => date('Y-m-d H:i:s', ($t['updated_time']+1)),
														'id' => $t['post_id']//,
														//'extra' => $friendsTimeline ? false : 'd'
														),
									'Account' => array(
														array(
															'id' => $account['Account']['id'],
															'Community' => array(
																					'name' => $account['Community']['name']
																					),
															'username' => $user[0]['name'],
															'avatar' => $user[0]['pic_small'] ? $user[0]['pic_small'] : './img/no_avatar.png',
															'url' => $t['permalink'],
															'targetuser' => $account['Account']['username']
															)
														)
									);
				}
			}
		}
		return $timeline;
	}
}
?>
